//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package roadmap_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/roadmap_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type TagInfoDbItem struct {
	Tag       string `bson:"_id"`
	Name      string `bson:"name"`
	TimeStamp int64  `bson:"timeStamp"`
}

func (item *TagInfoDbItem) ToTagInfo() *roadmap_api.TagInfo {
	return &roadmap_api.TagInfo{
		Tag:  item.Tag,
		Name: item.Name,
	}
}

type _TagDao struct {
	mc *mongo.Collection
}

func newTagDao(db *mongo.Database) (*_TagDao, error) {
	mc := db.Collection(db_ns.DB_NS_ROADMAP + "tag")
	return &_TagDao{mc: mc}, nil
}

func (db *_TagDao) Insert(ctx context.Context, dbItem *TagInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_TagDao) Exist(ctx context.Context, tag string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": tag})
	return count > 0, err
}

func (db *_TagDao) Get(ctx context.Context, tag string) (*TagInfoDbItem, error) {
	retItem := &TagInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": tag}).Decode(retItem)
	return retItem, err
}

func (db *_TagDao) Remove(ctx context.Context, tag string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": tag})
	return err
}

func (db *_TagDao) List(ctx context.Context) ([]*TagInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{}, options.Find().SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*TagInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_TagDao) Update(ctx context.Context, tag, name string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": tag}, bson.M{
		"$set": bson.M{
			"name": name,
		},
	})
	return err
}
